<template>
    <div class="goods_spec_form_container">
        <el-card class="box-card spec_card" shadow="never">
            <div slot="header" class="clearfix">
                <div class="header_container">
                    <span class="title">物料规格设置</span>
                    <div>
                        <el-button @click="toggleSpecTip">{{showSpecTipText}}</el-button>
                    <el-button type="primary" @click="initDefaultSpec">只有一个标准规格</el-button>
                    <el-button type="warning" @click="openSpecDialog">添加规格设置</el-button>
                    </div>
                </div>
                <el-alert v-if="showSpecTip"
                type="warning">
                    操作说明：
                    <br/>1、先“添加规格设置”，例子：规格名称：容量，规格值：1升。同一个规格名称的多个规格值可通过逗号分割一次性录入，保存后会自动生成多条记录，例如：1升,2升,3升。设置了所有规格后再点击“根据规格设置生成货品”，最后输入货品价格后点击“确定”保存。
                    货品可被删除，但库存数量大于0的无法删除。
                    <br/>2、没有多规格时，可直接点击“只有一个标准规格”进行快速设置。
                </el-alert>
            </div>
            <vxeTableTemplate ref="specTable" key="specTable"
                              :data="dataList" :options.sync="tableOptions" />
        </el-card>
        <el-card class="box-card product_card" shadow="never">
            <div slot="header" class="clearfix">
                <div class="header_container">
                    <span class="title">按规格划分的货品清单</span>
                    <el-button type="primary" @click="updateProductBySpec">根据规格设置生成货品</el-button>
                </div>
            </div>
            <vxeTableTemplate ref="productTable" key="productTable"
                              :data="goodsProductDataList" :options.sync="goodsProductTableOptions" />
        </el-card>
    </div>
</template>

<script>
import SpecForm from "./SpecForm";
import UpDownFunction from "@common/utils/UpDownFunction";

export default {
    name: "GoodsSpecForm",
    props: {
        row: {
            type: Object,
            default: null,
        },
    },
    data() {
        let _this = this;
        return {
            showSpecTip: false,
            showSpecTipText:'操作提示',
            //新增、编辑Dialog
            dialogOptions: { title: '物料规格设置', visible: false },
            dataList: [],
            tableOptions: {
                ref: "goodsSpecsTable",
                container: ".goods_specs_container",
                maxHeight: 230,
                editRules: {
                    specification: [
                        { required: true, message: '请输入规格名称', trigger: 'blur' },
                    ],
                    value: [
                        { required: true, message: '请输入规格值', trigger: 'blur' },
                    ],
                },
                columns: [
                    {
                        label: '规格名称',
                        prop: 'specification',
                        align: 'center',
                    },
                    {
                        label: '规格值',
                        prop: 'value',
                        align: 'center',
                    },
                ],
                operates: {
                    fixed: 'right',
                    list: [
                        {
                            id: "addSpecValue",
                            icon: "fa fa-plus",
                            type: "default",
                            tooltip: {
                                content: "增加规格值",
                            },
                            permission: "",
                            show: true,
                            method: (key, row, index) => {
                                _this.openSpecDialog(row);
                            },
                        },
                        {
                            id: "del",
                            icon: "fa fa-trash-o",
                            type: "danger",
                            tooltip: {
                                content: "删除",
                            },
                            permission: "",
                            show: true,
                            method: (key, row, index) => {
                                _this.delRow(row);
                            },
                        },
                        {
                            id: "top",
                            icon: "el-icon-top",
                            type: "primary",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "上移",
                            },
                            permission: "",
                            disabledFn(row) {
                                return row._index === 0;
                            },
                            method: (key, row) => {
                                _this.moveData(row, -1);
                            },
                        },
                        {
                            id: "bottom",
                            icon: "el-icon-bottom",
                            type: "success",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "下移",
                            },
                            permission: "",
                            disabledFn(row) {
                                return row._index === _this.dataList.length - 1;
                            },
                            method: (key, row) => {
                                _this.moveData(row, 1);
                            },
                        },
                    ],
                },
                pagination: false,
                getMaxHeight() {
                    let height = $(_this.getActiveTabsContainer()).height() * 0.8 - 200;
                    return height / 2;
                },
            },
            goodsProductDataList: [],
            goodsProductTableOptions: {
                ref: "goodsProductSpecsTable",
                container: ".goods_product_container",
                maxHeight: 280,
                editRules: {
                    price: [
                        { required: true, message: '请输入货品价格', trigger: 'blur' },
                    ],
                },
                columns: [
                    {
                        label: '货品规格',
                        prop: 'specifications',
                        align: 'center',
                        render: (h, { row }) => {
                            if (row.specifications) {
                                let specificationArr = JSON.parse(row.specifications);
                                let arr = specificationArr.map(item => {
                                    return h("el-tag", {
                                        style: {
                                            'margin-right': '5px',
                                        },
                                        props: {},
                                    }, item.value);
                                });
                                return h('div', {}, arr);
                            } else {
                                return h('div', {});
                            }
                        }
                    },
                    {
                        label: '库存数量',
                        prop: 'stock_sum_qty',
                        align: 'center',
                    },
                    {
                        label: '货品价格',
                        prop: 'price',
                        align: 'center',
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 4),
                        editRender: {
                            name: "CustomInput",
                            autofocus: 'input.el-input__inner',
                            autoselect: true,
                            props: {
                                doubleInput: {
                                    len: 4,
                                    negative: false,
                                },
                                clearable: true,
                            },
                            events: {
                                change: _this.rewritePriceRemain,
                            },
                        },
                    },
                ],

                operates: {
                    fixed: 'right',
                    list: [
                        {
                            id: "delProduct",
                            icon: "fa fa-trash-o",
                            type: "danger",
                            tooltip: {
                                content: "删除",
                            },
                            permission: "",
                            show: true,
                            method: (key, row, index) => {
                                _this.delProduct(row);
                            },
                        },
                    ],
                },
                pagination: false,
                getMaxHeight() {
                    let height = $(_this.getActiveTabsContainer()).height() * 0.8 - 200;
                    return height / 2;
                },
            },
            totalStockSumQty: 0,
            deleteSpecsSids: [],
        }
    },
    watch: {
        row: {
            handler() {
                this.init();
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        async init() {
            const _this = this;
            if (!_this.row) {
                return;
            }
            _this.dataList = [];
            _this.initGoodsSpecList(_this.row);
            _this.initGoodsProductsList(_this.row);
            // _this.initProductQtyByGoodsSid(_this.row);
        },
        // 获取物料
        initGoodsSpecList(row) {
            let _this = this;
            return _this.fetchData(_this.$api.API_GetJxcGoodsSpecsListByGoodsSid, {
                goods_sid: row.sid,
            }).then(res => {
                _this.dataList = _this.resetIndex(res.data);
            }).catch(() => {
            });
        },
        // 货品信息
        initGoodsProductsList(row) {
            let _this = this;
            return _this.fetchData(_this.$api.API_GetJxcGoodsProductsList, {
                goods_sid: row.sid,
            }).then(res => {
                _this.goodsProductDataList = res.data || [];
            }).catch(() => {
            });
        },
        // 获取物料货品总数数量
        initProductQtyByGoodsSid(row) {
            let _this = this;
            _this.totalStockSumQty = 0;
            return _this.fetchData(_this.$api.API_GetProductQtyByGoodsSid, {
                goods_sid: row.sid,
            }).then(res => {
                _this.totalStockSumQty = res.data || 0;
            }).catch(() => {
            });
        },
        toggleSpecTip(){
            let _this = this;
            _this.showSpecTip = !_this.showSpecTip;
            _this.showSpecTipText = _this.showSpecTip?"隐藏提示":"操作提示";
        },
        // 新增规格属性
        openSpecDialog(src_spec) {
            let _this = this;
            if (!_this.$utils.isNotEmpty(_this.row.sid)) {
                return;
            }
            _this.$dialog({
                title: '添加规格',
                width: '420px',
                component: {
                    value: SpecForm,
                    props: {
                        row: {
                            goods_sid: _this.row.sid,
                            specification:src_spec?src_spec.specification:'',
                        },
                    },
                },
                confirmBtn: {
                    type: 'primary',
                    text: '确定',
                    loading: true,
                    click (dialog, { component }) {
                        component && typeof component.confirm === 'function' && component.confirm().then(data => {
                            if (data) {
                                _this.initGoodsSpecList(_this.row);
                                dialog.visible = false;
                            }
                        });
                    },
                },
            });
        },
        // 增加行
        addRow(row) {
            let _this = this;
            let list = _this.dataList.map(item => $.extend({}, item));
            list.push(row);
            _this.dataList = _this.resetIndex(list);
            _this.initGoodsProductsList(_this.row);
            // _this.sortClass();
        },
        // 删除行
        delRow(row) {
            let _this = this;
            _this.$confirm("是否确认删除？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                _this.deleteSpec(row);
                let list = _this.dataList.filter(item => item._index !== row._index);
                _this.dataList = _this.resetIndex(list);
                // _this.sortClass();
                // if (row.sid) {
                //     _this.deleteSpecsSids.push(row.sid)
                // }
                _this.initGoodsProductsList(_this.row);
            }).catch(() => {
            });
        },
        // 删除规格
        deleteSpec(row) {
            let _this = this;
            if (!row || !row.sid) {
                return;
            }
            let sids = [row.sid];
            _this.fetchData(_this.$api.API_DeleteJxcGoodsSpecifications, {
                sids,
            }).then(() => {
                _this.$message.success('删除成功！');
                _this.initGoodsProductsList(_this.row);
            }).catch(() => {
            });
        },
        // 删除货品
        delProduct(row) {
            let _this = this;
            if (!row || !row.sid) {
                return;
            }
            _this.$confirm("是否确认删除？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                let sids = [row.sid];
                _this.fetchData(_this.$api.API_DeleteJxcGoodsProducts, {
                    sids,
                }).then(() => {
                    _this.$message.success('删除成功！');
                    _this.initGoodsProductsList(_this.row);
                }).catch(() => {
                });
            }).catch(() => {
            });
        },
        updateProductBySpec(){
            const _this = this;
            _this.fetchData(_this.$api.API_UpdateGoodsProductBySpecification, {
                goods_sid:_this.row.sid,
            }).then(() => {
                _this.initGoodsProductsList(_this.row);
            });
        },
        //初始化1个标准规格
        initDefaultSpec(){
            const _this = this;
            if (_this.dataList && _this.dataList.length>0){
                _this.$message.error('该物料已设置了规格，不能执行此操作！');
                return;
            }
            let subData = {goods_sid:_this.row.sid,specification:'标准规格',value:'标准规格'};
            _this.fetchData(_this.$api.API_SaveJxcGoodsSpecification, subData).then(result => {
                    _this.dataList = [result.data];
                    _this.updateProductBySpec();
            }).catch(() => {
                });
        },
        moveData(row, type) {
            const _this = this;
            let dataList = _this.dataList.map(item => $.extend({}, item));
            let fun = new UpDownFunction(dataList, row._index);
            if (type === 1) {
                dataList = fun.downData();
            } else {
                dataList = fun.upData();
            }
            dataList.forEach((item, index) => {
                item.sn = index + 1;
            });
            _this.dataList = _this.resetIndex(dataList);
            _this.batchSaveJxcGoodsSpec(`${ type === 1 ? '下移' : '上移' }成功！`);
            // _this.sortClass();
        },
        // 重写金额格式
        rewritePriceRemain({ row, column }) {
            let $this = this;
            let columnPrams = $.extend({}, column.params);
            let price = 0;
            if (row.price) {
                price = row.price;
            }
            $this.$set(row, columnPrams.prop, parseFloat(price).toFixed(4));
        },
        // sortClass() {
        //     let _this = this;
        //     let sortData = _this.dataList
        //     const groupBy = (array, f) => {
        //         let groups = {};
        //         array.forEach((o) => {
        //             let group = JSON.stringify(f(o));
        //             groups[group] = groups[group] || [];
        //             groups[group].push(o);
        //         });
        //         return Object.keys(groups).map((group) => {
        //             return groups[group];
        //         });
        //     };
        //     const sorted = groupBy(sortData, (item) => {
        //         return item.specification; // 返回需要分组的对象
        //     });
        //     _this.calculateCombination(sorted);
        //     return sorted;
        // },
        // calculateCombination(inputList) {
        //     let _this = this;
        //     let combination = [];
        //     let n = inputList.length;
        //     for (let i = 0; i < n; i++) {
        //         combination.push(0);
        //     }
        //     let i = 0;
        //     let isContinue = false;
        //     _this.goodsProductDataList = [];
        //     if (n === 0) {
        //         return;
        //     }
        //     do {
        //         let arr = [];
        //         for (let j = 0; j < n; j++) {
        //             arr.push({
        //                 sid: inputList[j][combination[j]].sid,
        //                 specification: inputList[j][combination[j]].specification,
        //                 value: inputList[j][combination[j]].value,
        //             });
        //         }
        //         let jsonStr = JSON.stringify(arr);
        //         _this.goodsProductDataList.push({
        //             goods_sid: _this.row.sid,
        //             specifications: jsonStr,
        //             price: 0,
        //             qty: 0,
        //             avg_in_price: 0,
        //         });
        //         i++;
        //         combination[n - 1] = i;
        //         for (let j = n - 1; j >= 0; j--) {
        //             if (combination[j] >= inputList[j].length) {
        //                 combination[j] = 0;
        //                 i = 0;
        //                 if (j - 1 >= 0) {
        //                     combination[j - 1] = combination[j - 1] + 1;
        //                 }
        //             }
        //         }
        //         isContinue = false;
        //         combination.forEach(item => {
        //             if (item !== 0) {
        //                 isContinue = true;
        //             }
        //         });
        //     } while (isContinue);
        // },
        // 获取物料规格
        async getTableData() {
            let _this = this;
            if (_this.$refs['xTable']) {
                let goodsSpecsTable = _this.$refs['xTable'].$refs['goodsProductSpecsTable'];
                let errMap = await goodsSpecsTable.validate(true).catch(errMap => errMap);
                if (errMap) {
                    return undefined;
                } else {
                    return _this.goodsProductDataList;
                }
            }
        },
        // 保存
        batchSaveJxcGoodsSpec(message) {
            let _this = this;
            return _this.fetchData(_this.$api.API_BatchSaveJxcGoodsSpecification, {
                specsList: _this.dataList
            }).then(() => {
                _this.$message.success(message);
            }).catch(() => {
            });
        },
        async confirm() {
            const _this = this;
            if (!_this.$utils.isNotEmptyList(_this.goodsProductDataList)) {
                _this.$message.warning('物料货品列表不能为空！');
                return false;
            }
            let errMap = false;
            if (_this.goodsProductSpecsTable) {
                errMap = await _this.goodsProductSpecsTable.validate(true).catch(errMap => errMap);
            }
            if (errMap) {
                return false;
            }
            let list = _this.goodsProductDataList.map(item => $.extend({}, item));
            return _this.fetchData(_this.$api.API_BatchSaveJxcGoodsProduct, {
                list,
                deleteSpecsSids: _this.deleteSpecsSids
            }).then(() => {
                _this.$message.success('保存成功！');
                return true;
            }).catch(() => {
                return false;
            });
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.goods_spec_form_container {
    width: 100%;
    height: 100%;
    overflow: hidden;

    .spec_card {
        margin-bottom: 10px;
    }

    /deep/ .header_container {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 5px;

        .title {
            font-size: 24px;
            font-weight: bold;
        }
    }
}
</style>
